package com.chenqq.qsocket.fractory;



import com.chenqq.qsocket.configuration.MinaConfigInfo;
import com.chenqq.qsocket.message.KeepAliveMessage;
import com.chenqq.qsocket.message.SocketMessage;
import com.chenqq.qsocket.tools.HexDump;
import com.chenqq.qsocket.tools.LogShow;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoder;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

import java.nio.ByteOrder;

/**
 * TCP编码器 可以自定义
 */
public class TCPEncoder implements ProtocolEncoder {
    @Override
    public void encode(IoSession ioSession, Object message, ProtocolEncoderOutput protocolEncoderOutput) throws Exception {
        IoBuffer buff = IoBuffer.allocate(200).setAutoExpand(true);
        if (message instanceof SocketMessage){
            SocketMessage msg = (SocketMessage) message;
            buff.order(ByteOrder.BIG_ENDIAN);
            buff.put(SocketMessage.HEADER1);
            buff.put(SocketMessage.HEADER2);
            buff.put(msg.getType());
            byte[] body = msg.getBody();
            short bodyLength = (short) body.length;
            buff.putShort(bodyLength);
            buff.put(body);
        }else {
            byte[] bytes = message.toString().getBytes(MinaConfigInfo.getInStance().getCharset());
            buff.put(bytes);
        }
        buff.flip();
        protocolEncoderOutput.write(buff);
    }

    @Override
    public void dispose(IoSession ioSession) throws Exception {

    }
}
